<template>
  <div ref="changeCompanyModal" class="modal">
    <a-modal
      :title="modalTitle"
      :visible="visible"
      @cancel="handleCancel"
      centered
      :getContainer="changeCompanyModal"
      :zIndex="1001"
    >
      <section class="content">
        <section v-if="step == 1">
          <ul class="list">
            <li
              class="item"
              v-for="org of orgList"
              :key="org.id"
              @click="handleCompanyChange(org.id)"
            >
              <div class="left">
                <img
                  class="logo"
                  v-if="org.square_logo"
                  :src="org.square_logo"
                />
                <div class="logo icon" v-else>
                  <cu-icon type="org-chuangjianjigou" />
                </div>
                <div class="name">
                  {{ org.company }}
                  <a-tag
                    color="blue"
                    v-if="$store.getters.userInfo.org_id == org.id"
                  >
                    当前企业
                  </a-tag>
                </div>
              </div>
              <div class="right">
                <SwapOutlined />
              </div>
            </li>
          </ul>
        </section>

        <section v-if="step == 2">
          <ul class="list">
            <li
              class="item item2"
              @click="addNewCompany('create')"
              v-if="config.can_reg_org"
            >
              <div class="left">
                <div class="logo icon">
                  <PlusSquareOutlined />
                </div>
                <div class="name">创建新企业</div>
              </div>
              <div class="right">
                <RightOutlined />
              </div>
            </li>
            <li class="item item2" @click="addNewCompany('join')">
              <div class="left">
                <div class="logo icon">
                  <UsergroupAddOutlined />
                </div>
                <div class="name">加入已有企业</div>
              </div>
              <div class="right">
                <RightOutlined />
              </div>
            </li>
          </ul>
        </section>
        <section v-if="step == 3">
          <div class="form" v-if="formType == 'join'">
            <div class="tip">
              企业邀请码是一个由字母组成的 8 位编码，可通过管理员获取。
            </div>
            <a-input
              class="mt-20"
              placeholder="请输入企业邀请码"
              v-model:value="joinForm.join_code"
            />
          </div>
          <div class="form" v-if="formType == 'create'">
            <div class="tip">
              注册新企业，并填写真实信息。楼宇管理数字化，助力效率提升。
            </div>
            <a-space direction="vertical" class="w-100p mt-20" size="large">
              <a-input
                v-model:value="createForm.company"
                placeholder="请输入企业名称"
              />
              <a-cascader
                style="width: 100%"
                v-model:value="createForm.areaValue"
                :options="areaOptions"
                :load-data="loadAreaData"
                placeholder="请选择省市区"
                change-on-select
                @change="areaSelectChange"
              />
              <a-select
                style="width: 100%"
                v-model:value="createForm.type"
                placeholder="请选择主营业态"
                :options="villageTypeList"
                v-if="villageTypeList.length"
              >
              </a-select>
            </a-space>
          </div>
        </section>
      </section>

      <template #footer>
        <div v-if="isWorkAiOrg"></div>
        <section class="footer" v-else>
          <div class="link option" v-if="step == 1" @click="nextStep">
            <span class="mr-2">加入或创建新企业</span>
            <RightOutlined style="font-size: 12px" />
          </div>
          <template v-else>
            <a-button @click="lastStep">上一步</a-button>
            <a-button
              v-if="step > 2"
              @click="submit"
              :disabled="submitDisabled"
              type="primary"
              >提交</a-button
            >
          </template>
        </section>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { computed, defineComponent, reactive, toRefs, watch } from "vue";
import {
  SwapOutlined,
  PlusSquareOutlined,
  UsergroupAddOutlined,
  RightOutlined,
} from "@ant-design/icons-vue";
import request from "../../../../common/utils/request";
import store from "../../../../store";
import { Modal, message } from "ant-design-vue";
import utils from "../../../../common/utils/utils";

export default defineComponent({
  name: "OrgChangeCompany",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: {
    SwapOutlined,
    PlusSquareOutlined,
    UsergroupAddOutlined,
    RightOutlined,
  },
  setup(props, context) {
    const state = reactive({
      changeCompanyModal: null,
      orgList: [],
      step: 1,
      formType: "",
      areaOptions: [],
      villageTypeList: [],
    });

    const joinForm = reactive({
      join_code: "",
    });

    const createForm = reactive({
      company: "",
      areaValue: [],
      type: undefined,
    });

    const getVillageTypeList = () => {
      if (!state.villageTypeList.length) {
        request.get("/village", "/village/type/list").then((res) => {
          state.villageTypeList = res.list.map((item) => ({
            label: item.name,
            value: item.alias,
          }));
          createForm.type = state.villageTypeList[0].value;
        });
      } else {
        createForm.type = state.villageTypeList[0].value;
      }
    };

    const getAreaInfo = () => {
      if (!state.areaOptions.length) {
        request.get("/public", "/district/province_list").then((res) => {
          if (res.list) {
            state.areaOptions = res.list.map((item) => ({
              value: item.area_code,
              label: item.short_name,
              level: 1,
              isLeaf: false,
            }));
          }
        });
      }
    };

    const getOrgList = () => {
      console.log(store.getters.userInfo.org_id);
      request.get("/org", "/user/orgList").then((res) => {
        state.orgList = res.list;
      });
    };

    const stepMap = {
      1: {
        title: "切换企业",
      },
      2: {
        title: "加入或创建新企业",
      },
      3: {
        join: "请输入企业邀请码",
        create: "设置企业信息",
      },
    };
    const modalTitle = computed(() => {
      if (state.step == 3) {
        return stepMap[state.step][state.formType];
      } else {
        return stepMap[state.step].title;
      }
    });

    const submitDisabled = computed(() => {
      if (state.formType == "join" && joinFormFinish()) {
        return false;
      }
      if (state.formType == "create" && createFormFinish()) {
        return false;
      }
      return true;
    });

    const joinFormFinish = () => {
      return !!joinForm.join_code;
    };

    const createFormFinish = () => {
      return (
        createForm.company && createForm.areaValue.length && createForm.type
      );
    };

    // 切换企业
    const handleCompanyChange = (id) => {
      request.post("/org", "/user/orgChange", { org_id: id }).then((res) => {
        utils.clearStorage();
        if (res && res.token) {
          utils.setStorage("org_token", res.token);
        }
        message.success("切换成功！");
        setTimeout(() => {
          location.replace(location.origin + location.pathname);
        }, 200);
      });
    };

    // 加入新企业
    const addNewCompany = (type) => {
      state.formType = type;
      nextStep();
    };

    // 上一步
    const lastStep = () => {
      state.step--;
      state.formType = "";
    };

    // 下一步
    const nextStep = () => {
      state.step++;
      if (state.step == 3) {
        getVillageTypeList();
        getAreaInfo();
      }
    };

    // 提交
    const submit = () => {
      let requestUrl = "";
      let params = {
        realname: store.getters.userInfo.realname,
        needMsg: true,
      };
      if (state.formType == "join") {
        requestUrl = "/user/orgJoin";
        params = {
          ...params,
          ...joinForm,
        };
      }
      if (state.formType == "create") {
        requestUrl = "/user/orgCreate";
        params = {
          ...params,
          ...createForm,
        };
        params.province_id = createForm.areaValue[0];
        params.city_id = createForm.areaValue[1];
        delete params.areaValue;
        const districtName = `${selectedAreaOptions[0].label},${selectedAreaOptions[1].label}`;
        params.district_name = districtName;
      }
      request.post("/org", requestUrl, params).then((res) => {
        context.emit("close");
        Modal.success({
          content: res.msg,
          centered: true,
        });
      });
    };

    let selectedAreaOptions = [];
    const areaSelectChange = (value, selectedOptions) => {
      selectedAreaOptions = selectedOptions;
    };

    const loadAreaData = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      const requestUrl =
        targetOption.level == 1
          ? "/district/city_list"
          : "/district/district_list";
      const params =
        targetOption.level == 1
          ? { province_id: targetOption.value }
          : { city_id: targetOption.value };
      request
        .get("/public", requestUrl, params)
        .then((res) => {
          if (res.list) {
            targetOption.children = res.list.map((item) => ({
              label: item.short_name,
              value: item.area_code,
              level: targetOption.level + 1,
              isLeaf: targetOption.level > 1,
            }));
          }
        })
        .finally(() => {
          targetOption.loading = false;
        });
      state.areaOptions = [...state.areaOptions];
    };

    const handleCancel = () => {
      context.emit("close");
    };

    const init = () => {
      if (state.orgList.length == 0) {
        getOrgList();
      }
    };

    const reset = () => {
      state.step = 1;
      state.formType = "";
      joinForm.join_code = "";
      createForm.company = "";
      createForm.areaValue = [];
      createForm.type = undefined;
    };
    const config = computed(() => store.getters.basicConfig);

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          init();
        } else {
          reset();
        }
      }
    );

    // 是否workAiOrg
    const isWorkAiOrg = computed(() => {
      if (
        store.getters.orgInfo &&
        store.getters.orgInfo.org_type &&
        store.getters.orgInfo.org_type == "workAi"
      ) {
        return true;
      } else {
        return false;
      }
    });

    return {
      modalTitle,
      joinForm,
      createForm,
      submitDisabled,
      loadAreaData,
      areaSelectChange,
      ...toRefs(state),
      handleCancel,
      handleCompanyChange,
      lastStep,
      nextStep,
      addNewCompany,
      submit,
      config,
      isWorkAiOrg,
    };
  },
});
</script>

<style lang="less" scoped>
.content {
  // min-height: 400px;
  .list {
    border: 1px solid #dddddd;
    padding: 10px;
    border-radius: 8px;
    .item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px;
      cursor: pointer;
      border-radius: 6px;
      &:hover {
        background-color: #f7f7f7;
      }
      .left {
        flex: 1;
        display: flex;
        align-items: center;
        .logo {
          width: 32px;
          height: 32px;
          border-radius: 24%;
          border: 1px solid #f1f1f1;
        }
        .name {
          margin-left: 10px;
          font-size: 14px;
          color: #000;
        }
        .icon {
          font-size: 16px;
          background: #f4f4f4;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .right {
        width: 40px;
        text-align: right;
        font-size: 14px;
      }
    }
    .item2 {
      .right {
        color: #999;
        font-size: 14px;
      }
    }
  }
}
.option {
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.form {
  margin-top: -16px;
  .tip {
    color: #666666;
    font-size: 12px;
  }
}

.modal {
  &:deep(.ant-modal-header) {
    border: none !important;
  }
  &:deep(.ant-modal-footer) {
    border: none !important;
  }
}
</style>
